package com.mohe.shanpao.lucene;

import java.io.IOException;
import java.nio.file.Paths;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;

public class SearchFiles {
	private SearchFiles() {}
	
	
	public static void main(String[] args) throws IOException, ParseException {
		String index = "index";
		String field = "contents";
		
		IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(index)));
		IndexSearcher searcher = new IndexSearcher(reader);
		
		Analyzer analyzer = new StandardAnalyzer();
		
		QueryParser parser = new QueryParser(field, analyzer);
		
		String key = "";
//		TermQuery
		Query query = parser.parse(key);
		
		TopDocs docs = searcher.search(query, 100);
		ScoreDoc[] sDocs = docs.scoreDocs;
		for(ScoreDoc sDoc : sDocs)
		{
			Document document = searcher.doc(sDoc.doc);
			System.out.println(document.get("path"));
			
		}
		doPagingSearch(searcher, query);
		
		reader.close();
	}
	
	static void doPagingSearch(IndexSearcher searcher, Query query) throws IOException
	{
		TopDocs results = searcher.search(query, 5);
		
		ScoreDoc[] hits = results.scoreDocs;
		
		int numTotalHits = results.totalHits;
		System.out.println(numTotalHits + " total matching documents");
		
	}
}
